<?php

namespace App\Services\SpiderContent;

use Carbon\Carbon;
use App\Models\User;
use App\Models\News;
use App\Jobs\RewardFirstParentJob;
use Illuminate\Support\Facades\Log;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Database\Eloquent\Collection;
use Sunra\PhpSimple\HtmlDomParser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

use DOMDocument;


class SpiderHuxiaoDeepContent
{

    public function execute($baseUrl)
    {
    	ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');

    	
    	//$url = "https://www.baidu.com";
    	$html = file_get_contents($baseUrl);

    	//$html = '<a href="aaaa"><div class="content-item"><div>测试</div></div></a>';
    	$dom = new DOMDocument();
    	

    	libxml_use_internal_errors(true);
    	//$html = htmlspecialchars($html);
    	
		
        $dom->loadHTML('<?xml encoding="UTF-8">' . $html);
      
        $elements = $dom->getElementsByTagName('div');

     	//$html = HtmlDomParser::str_get_html($html);

     	//dd($elements->nodeValue);

     	$data = [];
     	$i = 0;

     	$briefMatch = "/\"brief_id\":\d+,/";
     	$imgMatch = "/src=\".*?\"/";

     	$hoursMatch = "/\d+小时前/";
     	$MinutsMatch = "/\d+分钟前/";

        foreach($elements as $key=>$val){
        	$url = "";

    		if (strpos($val->getAttribute('class'), 'article-item-wrap') !== false) {
    			

    			$content =   $dom->saveHTML($val);
    			if(strstr($content,'分钟前') || strstr($content,'小时前')){
    				$data[$i]= ["images"=>"","brief"=>'',"content_cn"=>"","title_cn"=>"","images"=>"",'source'=>'huxiu',"created_at"=>Carbon::now(),"url"=>"","started_at"=>Carbon::now()];

    				$timeMatchContent  = preg_match($hoursMatch,$content,$match);

    	 			if(!empty($match)){
	    	 			preg_match('/\d+/',$match[0],$times);
	    	 			if(!empty($times)){

	    	 				$matchTime = $times[0];
	    	 				$data[$i]['started_at'] = Carbon::now()->subHours($matchTime);

	    	 			}

	    	 		}else{
	    	 			preg_match($MinutsMatch,$content,$match);
	    	 			if(!empty($match)){
	    	 				preg_match('/\d+/',$match[0],$times);
	    	 			}
	    	 			if(!empty($times)){

	    	 				$matchTime = $times[0];
	    	 				$data[$i]['started_at'] = Carbon::now()->subMinutes($matchTime);
	    	 				
	    	 			}	

	    	 		}

    				
    				$childNodes = $val->childNodes;
	    			$childNode = $childNodes[0];
				
					if($childNode->nodeName=="a"){

						$data[$i]['url'] = 'https://www.huxiu.com'.$childNode->getAttribute('href');

						$getImgNodes = $childNode->childNodes;
						foreach($getImgNodes as $ccNode){

							if($ccNode->nodeName=="div"){
								if($ccNode->childNodes){

									foreach($ccNode->childNodes as $imageNode){

										if($imageNode->nodeName=="img"){
											$data[$i]['title_cn'] = $imageNode->getAttribute('alt');
										}	

									}
								}
							}
							
						}
					}

					if(!empty($data[$i]['url'])){

						$itemContent = file_get_contents($data[$i]['url']);
						$contentDom = new DOMDocument();

	     		   		$contentDom->loadHTML('<?xml encoding="UTF-8">' . $itemContent);
	     		   		$imgElements =  $contentDom->getElementsByTagName('meta');
	     		   		
	     		   		foreach($imgElements as $imgElement){

	     		   			//dd($contentDom->saveHTML($imgElement));
	     		   			if (strpos($imgElement->getAttribute('property'), 'og:image') !== false) {
	     		   				$imageContent = file_get_contents($imgElement->getAttribute('content'));
	 							$newFileName = "/images/".Str::random(40) . '.jpg'; // 假设是JPG格式
								Storage::disk('oss')->put($newFileName, $imageContent);
								 
								// 你现在可以通过存储的路径访问图片
								$data[$i]['images'] = Storage::disk('oss')->path($newFileName);
	     		   				
	     		   			}
	     		   			
	     		   		}
	     		   		$divElements =  $contentDom->getElementsByTagName('div');
	     		   		foreach($divElements as $divElement){

	     		   			if (strpos($divElement->getAttribute('class'), 'ai-summary__content') !== false) {
	     		   				$data[$i]['brief'] = $contentDom->saveHTML($divElement);
	     		   			}

	     		   			if (strpos($divElement->getAttribute('class'), 'article__content') !== false) {
	     		   				$data[$i]['content_cn'] = $contentDom->saveHTML($divElement);
	     		   			}
	     		   			
	     		   		}

					}


					$i++;
					sleep(1);

    			}
    			
    			
    			
    	  }

        	
        	  
		}



		DB::table('deep_news')->insert($data);
		//dd($data);
     	 
    	//dd($elements);

     	//dd(retrieve_url_contents($url));
     	//$html = file_get_contents('https://www.huxiu.com/club/1000.html?object_type=51&object_id=1');
     	//dd($html);
 
		
    }


    public function djNodes($nodes,$res)
    {
    	if($nodes->nextSibling && $nodes->nextSibling->nodeName!="h4"){

    		$res['content'] = $res['content'].$nodes->nextSibling->textContent;


    		if($nodes->nextSibling->childNodes){

    			foreach($nodes->nextSibling->childNodes as $nn){
    				if($nn->nodeName=="img"){
    					$res['image'] = $nn->getAttribute('src');
    				}
    			}
    		}
    		
    		if(isset($nodes->nextSibling->nextSibling)  && $nodes->nextSibling->nextSibling->nodeName != "h4"){

    			 $res = $this->djNodes($nodes->nextSibling,$res);
    		}
    	}

    	return  $res;
    	//dd($nodes->nextSibling->nextSibling);
    	

    }

	function getUrlSize($url) {
	    // 初始化cURL

	   ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');

	    $ch = curl_init($url);
	     dd($ch);
	    // 设置cURL选项
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_HEADER, 1);
	    curl_setopt($ch, CURLOPT_NOBODY, 1);
	    
	    // 执行cURL请求
	    $output = curl_exec($ch);
	    // 获取内容长度
	    $size = 0;
	    if (preg_match('/Content-Length: (\d+)/', $output, $matches)) {

	        $size = (int)$matches[1];
	    }
	    
	    // 关闭cURL
	    curl_close($ch);
	    
	    return $size;
	}

	public function __invoke()
	{
	
		//Dinglog::text("========== refresh seckill product num start ......");

		$baseUrl = "https://www.huxiu.com/channel/105.html";
		$this->execute($baseUrl);

		//Dinglog::text("========== refresh seckill product num end ......");
	}
}
